﻿using System;
using System.Web.Http;
using PreeRegisterModel;
using System.Collections.Specialized;
using PreeRegisterBLL;
using PreeRegisterBLL.Security;
using System.Threading;
using System.Data;
using System.Collections.Generic;

namespace PreeRegister_WebAPI.Controllers
{
    public class synController : ApiController
    {
        [HttpPost]
        /// <summary>
        /// 接收绑定关系
        /// </summary>
        /// <param name="any"></param>
        /// <returns></returns>
        public EncodeModel bind(NameValueCollection any)
        {
            try
            {
                //获取JSON加密参数
                string head_json = CommonBLL.RequestGetParam("head").ToString();
                string body_json = CommonBLL.RequestGetParam("body").ToString();

                //拼装jsonData类
                EncodeModel encodeModel = new EncodeModel();
                encodeModel.head = head_json;
                encodeModel.body = body_json;

                //转化jsonData串
                string jsonData = csSerialize.ResponseInfo(encodeModel);

                SynBindResponseModel synBindResponseModel = new SynBindResponseModel();

                //解密头和内容信息
                string ErrMsg = "";
                string ReturnBodyJson = "";
                if (!ResultDecode.DecodeResult(jsonData, "", ref head_json, ref body_json, ref ErrMsg))
                {
                    //序列化返回内容类
                    ReturnBodyJson = csSerialize.SynBindResponseModel(synBindResponseModel);

                    //加密返回内容Json
                    return ResultDecode.EncodeResult(ReturnBodyJson);
                }

                //入口参数日志
                CommonBLL.WriteLog("syn|bind|Post|\r\n" + body_json + "\r\n\r\n");

                //反序列化请求字符串
                SynBindRequestModel synBindRequestModel = csSerialize.SynBindRequestModel(body_json);

                //绑定关系入库
                synBindResponseModel = SynBLL.SynBind(synBindRequestModel);

                //序列化返回内容类
                ReturnBodyJson = csSerialize.SynBindResponseModel(synBindResponseModel);

                //返回参数日志
                CommonBLL.WriteLog("syn|bind|Return|\r\n" + ReturnBodyJson + "\r\n\r\n");
                //如果绑定关系接收成功后，单起线程，同步检验报告
                if (synBindRequestModel.opcode == "1" && synBindResponseModel.state == "1")
                {
                    CommonBLL.WriteLog("线程开始，同步检验报告的患者ID：" + synBindRequestModel.pid + "\r\n\r\n");
                    Thread thr1 = new Thread(new ParameterizedThreadStart(SynReportList));
                    thr1.Priority = ThreadPriority.AboveNormal;
                    thr1.IsBackground = true;
                    thr1.Start(synBindRequestModel.pid);
                    thr1.Name = synBindRequestModel.pid;
                    CommonBLL.WriteLog(string.Format("线程开始2，线程名称1：{0}，线程名称2：{1}。\r\n\r\n"
                        , thr1.Name, Thread.CurrentThread.Name));
                    thr1.Join();
                    CommonBLL.WriteLog("线程结束，同步检验报告的患者ID：" + synBindRequestModel.pid + "\r\n\r\n");
                }
                return ResultDecode.EncodeResult(ReturnBodyJson);
            }

            catch (Exception err)
            {
                SynBindResponseModel synBindResponseModel = new SynBindResponseModel();
                synBindResponseModel.code = "0";
                synBindResponseModel.msg = err.ToString();
                //序列化返回内容类
                string ReturnBodyJson = csSerialize.SynBindResponseModel(synBindResponseModel);

                //返回参数日志
                CommonBLL.WriteLog("syn|bind|Return|\r\n" + ReturnBodyJson + "\r\n\r\n");

                //加密返回内容Json
                return ResultDecode.EncodeResult(ReturnBodyJson);
            }
        }

        /// <summary>
        /// 绑定关系接收成功后，推送该患者的检验报告
        /// </summary>
        /// <param name="pid">pid</param>
        private static void SynReportList(object pid)
        {
            string times = string.Empty;
            string patientCode = CommonBLL.GetAdnum(pid.ToString(), out times);
            ReportList(pid.ToString(), patientCode, times);
        }

        /// <summary>
        /// 检验报告推送
        /// </summary>
        /// <param name="pid">pid</param>
        /// <param name="patientCode">住院号</param>
        /// <param name="times">住院次数</param>
        private static void ReportList(string pid, string patientCode, string times)
        {
            int succ_count = 0;
            int error_count = 0;

            List<ReportListResponseModel> list = ReportBLL.GetReportList(patientCode, times);
            if (list != null && list.Count > 0)
            {
                PreeRegisterBLL.hars_reportlist bll_reportlist = new PreeRegisterBLL.hars_reportlist();
                string RDSP_URL = VariableBLL.RDSP_IPAdress_INHOSPService + "/report/get";
                for (int i = 0; i < list.Count; i++)
                {
                    try
                    {
                        ReportListResponseModel reportListResponseModel = list[i];
                        CommonBLL.WriteLog(string.Format("线程名称：{0},线程运行状态：{1}", Thread.CurrentThread.Name, Thread.CurrentThread.IsAlive));
                        Thread.Sleep(100);
                        //转换检验报告条目信息为json格式
                        string json_ReportList = csSerialize.ReportLsitResponseModel(reportListResponseModel);

                        //获取预约平台URL
                        ResponseModel responseModel = CommonBLL.SendInfo(RDSP_URL, json_ReportList);
                        if (responseModel.body.code == "1")
                        {
                            CommonBLL.WriteLog(string.Format("同步检验报告成功,PID：{0}，共{1}条，报告ID：{2}，第{3}条。",
                             pid, list.Count, reportListResponseModel.repid, i));
                            succ_count++;
                            bll_reportlist.Update(pid, reportListResponseModel.repid, "1", responseModel.body.msg);
                        }
                        else
                        {
                            CommonBLL.WriteLog(string.Format("同步检验报告失败,PID：{0}，共{1}条，报告ID：{2}，第{3}条。",
                            pid, list.Count, reportListResponseModel.repid, i));
                            error_count++;
                            //回置已发送标志
                            bll_reportlist.Update(pid, reportListResponseModel.repid, "2", responseModel.body.msg);
                        }
                        Thread.Sleep(100);
                    }
                    catch (Exception err)
                    {
                        CommonBLL.WriteLog(string.Format("线程运行状态：{0}。同步检验报告异常,异常信息：{1}。", Thread.CurrentThread.IsAlive, err.ToString()));
                        continue;
                        // Thread.CurrentThread.Abort();
                    }
                }
            }
            else
            {
                CommonBLL.WriteLog(string.Format("线程运行状态：{0}。未查询到患者ID为：{1}的检验报告。", Thread.CurrentThread.IsAlive, pid));
            }

            Thread.CurrentThread.Abort();
        }

    }
}
